package com.collect.tanzania.zhiScene.zhiPublic;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;

import androidx.annotation.NonNull;

import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.collect.tanzania.R;
import com.collect.tanzania.zhiBase.BaseActivity;
import com.collect.tanzania.zhiBean.zhiReceive.ZHIRAppVersionEntity;
import com.collect.tanzania.zhiBean.zhiReceive.ZHIRCheckInOutEntity;
import com.collect.tanzania.zhiBean.zhiReceive.ZHIRGroupUserEntity;
import com.collect.tanzania.zhiBean.zhiReceive.ZHIRLoginEntity;
import com.collect.tanzania.zhiBean.zhiReceive.ZHIRUserCallRecordWarnEntity;
import com.collect.tanzania.zhiBean.zhiSend.ZHISLoginEntity;
import com.collect.tanzania.zhiBean.zhiSend.ZHISendEntity;
import com.collect.tanzania.zhiGlobal.zhiAppSettings.ZHIProjectConfigs;
import com.collect.tanzania.zhiGlobal.zhiAppSettings.ZHIProjectRouter;
import com.collect.tanzania.zhiHelper.ZHIAdvertIDHelper;
import com.collect.tanzania.zhiHelper.ZHIAppVersionHelper;
import com.collect.tanzania.zhiHelper.ZHIMainProcessHelper;
import com.collect.tanzania.zhiHelper.ZHICallLogHelper;
import com.collect.tanzania.zhiScene.zhiCheckIn.ZHICheckInReduce;
import com.collect.tanzania.zhiScene.zhiCollection.zhiGroup.zhiRoot.ZHIPerformanceReduce;
import com.collect.tanzania.zhiScene.zhiWidget.zhiDialog.ZHIDialogMessage;
import com.zhi.inisyccalllog.ASCallLogManager;
import com.zhi.syc.data_applist.ASGpsManagerGms;
import com.zhi.syc.data_applist.ASSycManager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

@SuppressLint("NonConstantResourceId")
@Route(path = ZHIProjectRouter.ZHI_Public_Splash)
public class ZHISplashActivity extends BaseActivity<ZHISplashPresenter> implements ZHISplashContract.View, EasyPermissions.PermissionCallbacks, EasyPermissions.RationaleCallbacks {
    @BindView(R.id.splash_c1)
    TextView splash_c1;

    private static final int RC_INSTALL_PCK = 10086;

    private ZHIDialogMessage dialogMessage;

    private ZHIRLoginEntity mZHIRLoginEntity;

    @Override
    protected void initInjector() {
        mActivityComponent.inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_splash_v2;
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void initView() {
        splash_c1.setText(getResources().getString(R.string.app_name_ct) + " v" + ZHIProjectConfigs.APP_VERSION);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onGetErrorInfo(String methodName) {
        String loginMethod = "getLoginInfoV2";
        if (methodName.contains(loginMethod) || loginMethod.contains(methodName)) {
            ZHIProjectRouter.toRegLoginV2();
            return;
        }
        String getGroupUsers = "getGroupUsers";
        if (methodName.equalsIgnoreCase(getGroupUsers)) {
            checkUserCallRecordWarn();
            return;
        }
        String getUserCallRecordWarn = "getUserCallRecordWarn";
        if (methodName.equalsIgnoreCase(getUserCallRecordWarn)) {
            checkInOutState();
            return;
        }
        String getCheckState = "getCheckState";
        if (methodName.equalsIgnoreCase(getCheckState)) {
            handlerLoginResult();
            return;
        }
        //弹框提示
        showNetErrDialog();
    }

    @Override
    public void onGetAppVersionInfoV2(ZHIRAppVersionEntity zhirAppVersionEntity) {
        boolean handlerResult = ZHIAppVersionHelper.getInstance().handlerAppVersion(this, zhirAppVersionEntity);
        if (!handlerResult) {
            checkLogin();
        }
    }

    @Override
    public void onGetLoginInfoV2(final ZHIRLoginEntity zhiRLoginEntity) {
        try {
            mZHIRLoginEntity = zhiRLoginEntity;
            checkGroupUser();

            if (ZHICallLogHelper.FLAG_OPEN) {
                //更新参数
                ASSycManager.getInstance().setCommonParams(ZHIProjectConfigs.APP_VERSION, ZHIMainProcessHelper.getInstance().getFullName(), ZHIAdvertIDHelper.getInstance().getGoogleAdvertId(), ZHIMainProcessHelper.getInstance().getToken(), ZHIMainProcessHelper.getInstance().getLoginId());
                ASCallLogManager.getInstance().setCommonParams(ZHIProjectConfigs.APP_VERSION, ZHIMainProcessHelper.getInstance().getFullName(), ZHIAdvertIDHelper.getInstance().getGoogleAdvertId(), ZHIMainProcessHelper.getInstance().getToken(), ZHIMainProcessHelper.getInstance().getLoginId());
                //同步
                ASSycManager.getInstance().sycDataForRisk();
                ASGpsManagerGms.getInstance().sycDataByConditionsV2();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onGetGroupUsers(ArrayList<ZHIRGroupUserEntity> zhirGroupUserEntityArrayList) {
        checkUserCallRecordWarn();
    }

    @Override
    public void onGetUserCallRecordWarn(ZHIRUserCallRecordWarnEntity zhirUserCallRecordWarnEntity) {
        try {
            if (zhirUserCallRecordWarnEntity != null && zhirUserCallRecordWarnEntity.isWarnFlag()) {
                ZHIDialogMessage.showDialog(ZHISplashActivity.this, "Prompt", zhirUserCallRecordWarnEntity.getWarnContent(), false, true, tag -> checkInOutState());
            } else {
                checkInOutState();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onGetCheckState(ZHIRCheckInOutEntity zhirCheckInOutEntity) {
        try {
            if (zhirCheckInOutEntity != null && zhirCheckInOutEntity.isToCheckIn()) {
                if (mZHIRLoginEntity != null) {
                    //人脸界面
                    if (mZHIRLoginEntity.isLiveFlag()) {
                        ZHIProjectRouter.toRegFaceV2();
                        return;
                    }
                }
                ZHIDialogMessage.showDialog(getActivity(), "Tips", "You haven't clocked in for work today", false, true, tag -> {
                    ZHICheckInReduce.mFromLoginSuccess = true;
                    ZHIProjectRouter.toCheckInForLogin();
                });
                return;
            }
            handlerLoginResult();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        getNeedPermissions();
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }

    @Override
    public void onRationaleAccepted(int requestCode) {
        getNeedPermissions();
    }

    @Override
    public void onRationaleDenied(int requestCode) {
        finish();
    }

    @AfterPermissionGranted(RC_CAMERA_AND_STORAGE)
    public void allPass() {
//        if (mPresenter != null) {
//            mPresenter.getAppVersionInfoV2(ZHISplashActivity.this, new ZHISendEntity());
//        }
        getInstallPckPermission();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            //当从软件设置界面，返回当前程序时候
            if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
                getNeedPermissions();
            } else if (requestCode == RC_INSTALL_PCK) {
                getInstallPckPermission();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showNetErrDialog() {
        if (dialogMessage == null) {
            dialogMessage = new ZHIDialogMessage(ZHISplashActivity.this);
            dialogMessage.setIsSingleBtn(false);
            dialogMessage.setTitle(getResources().getString(R.string.prompt));
            dialogMessage.setNegtive(getResources().getString(R.string.dialog_image_pick_cancel));
            dialogMessage.setMessage(getResources().getString(R.string.net_err_try_again));
            dialogMessage.setOnClickButtonListener(tag -> {
                dialogMessage.dismiss();
                if (1 == tag) {
                    //查询用户进度信息
                    assert mPresenter != null;
                    mPresenter.getAppVersionInfoV2(ZHISplashActivity.this, new ZHISendEntity());
                }
            });
        }
        dialogMessage.show();
    }

    private void checkVersion() {
        if (mPresenter != null) {
            mPresenter.getAppVersionInfoV2(ZHISplashActivity.this, new ZHISendEntity());
        }
    }

    private void checkGroupUser() {
        if (mPresenter != null) {
            ZHIPerformanceReduce.shouldReloadGroupUesrList();
            mPresenter.getGroupUsers(ZHISplashActivity.this, new ZHISendEntity());
        }
    }

    private void checkInOutState() {
        if (mPresenter != null) {
            mPresenter.getCheckState(ZHISplashActivity.this, new ZHISendEntity());
        }
    }

    private void checkLogin() {
        String gFullName = ZHIMainProcessHelper.getInstance().getFullName();
        String gPassword = ZHIMainProcessHelper.getInstance().getPassword();
        if (TextUtils.isEmpty(gFullName) || TextUtils.isEmpty(gPassword)) {
            ZHIProjectRouter.toRegLoginV2();
            return;
        }
        if (mPresenter != null) {
            ZHISLoginEntity ftsLoginEntity = new ZHISLoginEntity(gFullName, gPassword);
            mPresenter.getLoginInfoV2(ZHISplashActivity.this, ftsLoginEntity);
        }
    }

    private void checkUserCallRecordWarn() {
        if (mPresenter != null) {
            mPresenter.getUserCallRecordWarn(ZHISplashActivity.this, new ZHISendEntity());
        }
    }

    private void handlerLoginResult() {
        try {
            if (mZHIRLoginEntity != null) {
                //偷偷的上传通话记录
                if (ZHICallLogHelper.FLAG_OPEN) {
                    ZHICallLogHelper.getInstance().initAppUserIds(mZHIRLoginEntity.getUserId());
                }

                //人脸界面
                if (mZHIRLoginEntity.isLiveFlag()) {
                    ZHIProjectRouter.toRegFaceV2();
                    return;
                }

                //客服界面
                if (mZHIRLoginEntity.isCustomerFlag()) {
                    //电召界面
                    if (mZHIRLoginEntity.isCustomerWhitelistFlag()) {
                        ZHIProjectRouter.toRecallV2();
                        return;
                    }

                    //客服界面
                    ZHIProjectRouter.toCustomerServiceV2();
                    return;
                }

                //客服组长界面
                if (mZHIRLoginEntity.isCustomerDGroupFlag()) {
                    //客服界面
                    ZHIProjectRouter.toCustomerServiceAdmin();
                    return;
                }

                //电销界面
                if (mZHIRLoginEntity.isDxFlag()) {
                    ZHIProjectRouter.toRootTelemarketing();
                    return;
                }

                //电审界面
                if (mZHIRLoginEntity.isDhFlag()) {
                    ZHIProjectRouter.toRootDs();
                    return;
                }

                //单人审核界面
                if (mZHIRLoginEntity.isWholeKefuFlag()) {
                    ZHIProjectRouter.toRootAuditer();
                    return;
                }

                //大组长催收界面
                if (mZHIRLoginEntity.isBigGroupFlag()) {
                    ZHIProjectRouter.toRootBigGroup();
                    return;
                }

                //订单审核界面
                if (mZHIRLoginEntity.isOrderReviewFlag()) {
                    ZHIProjectRouter.toRootOrderReview();
                    return;
                }

                //催收界面
                if (mZHIRLoginEntity.isGroupFlag()) {
                    if (mZHIRLoginEntity.isLevelB1()) {
                        ZHIProjectRouter.toRootGroupB1();
                    } else if (mZHIRLoginEntity.isLevelB2()) {
                        ZHIProjectRouter.toRootGroupB2();
                    } else {
                        ZHIProjectRouter.toRootGroup();
                    }
                } else {
                    if (mZHIRLoginEntity.isLevelB1()) {
                        ZHIProjectRouter.toRootMemberB1();
                    } else if (mZHIRLoginEntity.isLevelB2()) {
                        ZHIProjectRouter.toRootMemberB2();
                    } else {
                        ZHIProjectRouter.toRootMember();
                    }
                }

            } else {
                ZHIProjectRouter.toRegLoginV2();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static final int RC_CAMERA_AND_STORAGE = 111;
    String[] reqPerms = {
            Manifest.permission.INTERNET,
            Manifest.permission.READ_CALL_LOG,
            Manifest.permission.WRITE_CALL_LOG,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_CONTACTS,
            Manifest.permission.WRITE_CONTACTS,
            Manifest.permission.CALL_PHONE,
            Manifest.permission.CAMERA,
            Manifest.permission.READ_SMS,
            Manifest.permission.ACCESS_WIFI_STATE,
            Manifest.permission.ACCESS_NETWORK_STATE,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.READ_PHONE_STATE
    };

    private void getNeedPermissions() {
        EasyPermissions.requestPermissions(this, getResources().getString(R.string.launch_permissions), RC_CAMERA_AND_STORAGE, reqPerms);
    }

    private void getInstallPckPermission() {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                if (getPackageManager().canRequestPackageInstalls()) {
                    checkVersion();
                } else {
                    getUnknowAppPage();
                }
            } else {
                checkVersion();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void getUnknowAppPage() {
        try {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
                intent.setData(Uri.parse("package:" + ZHIProjectConfigs.PACKAGE_NAME));
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivityForResult(intent, RC_INSTALL_PCK);
            } else {
                checkVersion();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}